<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 根据type属性进行搜索 修改为根据商品名或供应商名搜索 -->
      <el-select
        v-model="listQuery.type"
        placeholder="查询类别"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in searchOptions"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="listQuery.title"
        placeholder="关键字"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >增加商品</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="_id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品名" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.clazz }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品材质" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.material }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制作方法" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.method }}</span>
        </template>
      </el-table-column>
      <el-table-column label="适用规格" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.standard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专属规格" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.exclusive }}</span>
        </template>
      </el-table-column>
      <el-table-column label="包装规格" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.size }}</span>
        </template>
      </el-table-column>
      <el-table-column label="口味" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.flavor }}</span>
        </template>
      </el-table-column>
      <el-table-column label="特殊功用" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.special }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产地" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.origin }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产日期" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.date }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.warranty }}</span>
        </template>
      </el-table-column>
      <el-table-column label="特色" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.feature }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.count }}</span>
        </template>
      </el-table-column>

      <el-table-column label="Status" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ row.status=="1"?"上架":"下架" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="Actions"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button
            v-if="row.status!='1'"
            size="mini"
            type="success"
            @click="handleModifyStatus(row,'1')"
          >上架</el-button>
          <el-button v-if="row.status!='0'" size="mini" @click="handleModifyStatus(row,'0')">下架</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 新增或更新弹出层 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <!-- prop对于rules中的验证规则 -->
        <el-form-item label="商品名">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="temp.type" placeholder="Type" clearable>
            <el-option v-for="item in goodsTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="temp.clazz" />
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="temp.material" />
        </el-form-item>
        <el-form-item label="制作方法">
          <el-input v-model="temp.method" />
        </el-form-item>
        <el-form-item label="适用规格">
          <el-input v-model="temp.standard" />
        </el-form-item>
        <el-form-item label="专属规格">
          <el-input v-model="temp.exclusive" />
        </el-form-item>
        <el-form-item label="包装规格">
          <el-input v-model="temp.size" />
        </el-form-item>
        <el-form-item label="口味">
          <el-input v-model="temp.flavor" />
        </el-form-item>
        <el-form-item label="特殊功用">
          <el-input v-model="temp.special" />
        </el-form-item>
        <el-form-item label="产地">
          <el-input v-model="temp.origin" />
        </el-form-item>
        <el-form-item label="生产日期">
          <el-input v-model="temp.date" />
        </el-form-item>
        <el-form-item label="保质期">
          <el-input v-model="temp.warranty" />
        </el-form-item>
        <el-form-item label="特色">
          <el-input v-model="temp.feature" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="temp.price" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="temp.count" />
        </el-form-item>
        <!-- 文件上传 -->
        <el-upload
          class="upload-demo"
          :action="'/api/stores/goodsUpload/'+temp._id"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          list-type="picture"
        >
          <el-button 
            size="small"
            type="primary"
            :disabled="dialogStatus==='create'?true:false"
            >点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
      </div>
    </el-dialog>

    <!-- 评价弹出层 -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchPv,
  createArticle,
  updateArticle
} from "@/api/article";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
  createStoreGoods,
  getStoreGoods,
  updateStoreGoods,
  deleteStoreGoods
} from "@/api/store";

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null, //列表数据
      total: 0, //列表总数
      listLoading: true, //列表是否正在加载
      listQuery: {
        //列表查询条件
        page: 1, //当前页
        limit: 20, //每页条数
        // importance: undefined,//重要性
        title: undefined, //搜索时键名
        type: undefined, //搜索时键值 goodsName商品名 type商品类型
        sort: 1
      },
      statusOptions: [0, 1], //状态值 0下架，1 在售
      searchOptions: [
        {
          name: "商品名",
          value: "goodsName"
        },
        {
          name: "商品类型",
          value: "type"
        }
      ],
      goodsTypeOptions: [
        "主粮",
        "洗浴",
        "日用品",
        "零食",
        "保健品",
        "医疗",
        "清洁洗护",
        "玩具"
      ], //商品类别
      temp: {
        id: undefined,
        // importance: 1,//重要级
        name: "",
        type: "主粮", //商品类别
        clazz: "", //商品分类
        material: "", //商品材质
        method: "", //制作方法
        standard: "", //适用规格 需处理成数组
        exclusive: "", //专属规格
        size: "", //包装规格 需处理成数组
        flavor: "", //口味
        special: "", //特殊功用
        origin: "", //产地
        date: "", //生产日期
        warranty: "", //保质期
        storeId: undefined, //关联商家Id
        feature: "", //特色
        price: "", //价格 需处理成数组
        count: 0,
        imgs: [],//图片数组
        status: "1" //状态值 0下架，1 在售
      },
      dialogFormVisible: false, //增加商品form表单弹窗的显示或隐藏
      dialogStatus: "", //用于判断增加商品按钮显示是增加还是更新
      textMap: {
        // 弹出层的标题
        update: "更新商品",
        create: "增加商品"
      },
      dialogPvVisible: false, //评价弹出层
      pvData: [], //评价弹出层数据
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" }
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change"
          }
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" }
        ]
      },
      downloadLoading: false,
      //文件上传
      fileList: [
        {
          name: "food.jpeg",
          url:
            "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        },
        {
          name: "food2.jpeg",
          url:
            "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.listLoading = true;
      const res = await getStoreGoods(this.listQuery);
      await setTimeout(() => {
        this.listLoading = false;
      }, 0.5 * 1000);
      this.list = res.data.row;
      this.list = this.list.map(v => {
        v.standard = v.standard.join("、");
        v.size = v.size.join("、");
        v.flavor = v.flavor.join("、");
        v.price = v.price.join("、");
        return v;
      });
      this.total = res.data.total;
    },
    // 筛选 或者搜索
    handleFilter() {
      console.log("enter");

      this.listQuery.page = 1;
      this.getList();
    },
    // 更改表格中的状态 可用来做商品的上架和下架
    async handleModifyStatus(row, status) {
      const data = { ...row };
      data.standard = row.standard.split("、");
      data.size = row.size.split("、");
      data.flavor = row.flavor.split("、");
      data.price = row.price.split("、");
      data.status = status;
      const res = await updateStoreGoods(data);

      this.$message({
        message: "操作Success",
        type: "success"
      });
      row.status = status;
    },
    // 改变排序方式
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    // 按ID升序或降序排序
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    // 重置temp模板 初始化新增表单数据
    resetTemp() {
      this.temp = {
        id: undefined,
        // importance: 1,//重要级
        name: "",
        type: "主粮", //商品类别
        clazz: "", //商品分类
        material: "", //商品材质
        method: "", //制作方法
        standard: "", //适用规格 需处理成数组
        exclusive: "", //专属规格
        size: "", //包装规格 需处理成数组
        flavor: "", //口味
        special: "", //特殊功用
        origin: "", //产地
        date: "", //生产日期
        warranty: "", //保质期
        storeId: undefined, //关联商家Id
        feature: "", //特色
        price: "", //价格 需处理成数组
        imgs: [],//图片数组
        status: "1"
      };
    },
    // 点击增加商品按钮 弹出增加商品弹出层
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 增加商品点击提交 返回结果 成功刷新页面
    createData() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          const data = { ...this.temp };
          data.standard = this.temp.standard.split("、");
          data.size = this.temp.size.split("、");
          data.flavor = this.temp.flavor.split("、");
          data.price = this.temp.price.split("、");
          const res = await createStoreGoods(data);
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "新增成功",
            type: "success",
            duration: 2000
          });
          this.getList();
        }
      });
    },
    // 弹出更新表单
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 更新列表数据 更新表单的提交按钮触发
    updateData() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          const data = { ...this.temp };
          data.standard = this.temp.standard.split("、");
          data.size = this.temp.size.split("、");
          data.flavor = this.temp.flavor.split("、");
          data.price = this.temp.price.split("、");
          const res = await updateStoreGoods(data);
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
          this.getList();
        }
      });
    },
    // 删除列表数据
    async handleDelete(row, index) {
      const res = await deleteStoreGoods(row._id);
      console.log(res);

      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      this.getList();
    },

    // 获取排序的class名称 切换升降序
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },

    //文件上传事件
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击之前上传过的图片
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  }
};
</script>
